﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SQLite;
using BartonExtension;

namespace SqliteWrapper.Procedures
{
    public class Proc_AddComment : IProcedure
    {
        public override SqliteError doProcedure(object DataSource, string DBPath)
        {
            Comment comment = DataSource as Comment;
            SqliteError error = new SqliteError() { IsProcessSuccess = false, ErrorText = null };
            SqliteConnectionManager manager = SqliteConnectionManager.Create(DBPath);
            using (SQLiteWriteLock writeLock = new SQLiteWriteLock(manager.ConnectionString))
            {
                using (SQLiteConnection conn = manager.GetSqliteConnection())
                {
                    conn.Open();
                    using (SQLiteCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select count(*) from comment where uid = @UserId and createtimetag = @Date";
                        cmd.Parameters.Add("@Date", System.Data.DbType.String).Value = comment.Date;
                        int count = cmd.ExecuteScalar().toInt32().Value;
                        if (count == 0)
                        {
                            cmd.Parameters.Clear();
                            cmd.CommandText = "Insert into comment(bid,uid,refererid,comment,createtimetag) values(@BookId,@UserId,@RefererId,@Comment,@Date)";
                            cmd.Parameters.Add("@BookId", System.Data.DbType.UInt64).Value = comment.BookId;
                            cmd.Parameters.Add("@UserId", System.Data.DbType.UInt64).Value = comment.UserId;
                            cmd.Parameters.Add("@RefererId", System.Data.DbType.UInt64).Value = comment.RefererId;
                            cmd.Parameters.Add("@Comment", System.Data.DbType.String).Value = comment.Content;
                            cmd.Parameters.Add("@Date", System.Data.DbType.String).Value = comment.Date;
                            try
                            {
                                cmd.ExecuteNonQuery();
                                error.IsProcessSuccess = true;
                            }
                            catch (Exception ex)
                            {
                                error.ErrorText = ex.Message;
                            }
                        }
                        else
                        {
                            error.IsProcessSuccess = false;
                            error.ErrorText = "您今日已评论过,请明日再来";
                        }
                    }
                }
            }
            return error;
        }
    }
}
